<template>
  <div>
    <Layout />
    <el-container class="app-item-contain">
      <el-header class="align-center">
        <h1>{{ "正在考试" }}</h1>
        <div>
          <span class="question-title-padding"
            >试卷总分：{{ form.paper.totalScore }}</span
          >
        </div>
      </el-header>
      <el-main>
        <el-form
          :model="form"
          ref="form"
          v-loading="formLoading"
          label-width="100px"
        >
          <el-row :key="index" v-for="(problem, index) in form.problems">
            <br />
            <QuestionEdit
              :index="index + 1"
              :qType="problem.type"
              :question="problem"
              :answer="answer[index]"
            />
          </el-row>
          <el-row class="do-align-center">
            <el-button type="primary" @click="submitForm">提交</el-button>
          </el-row>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import { formatSeconds } from "@/utils";
import QuestionEdit from "../components/QuestionEdit";
import Layout from "@/layout";
import { autoGenerate, getAllPapers } from "@/api/autoGenerate";
import {
  attendExam,
  commitPractice,
  markAnswer,
  getExams,
  finishExam,
  getScores,
  getAnswers,
  getScore,
} from "@/api/exam";
// import examPaperAnswerApi from "@/api/examPaperAnswer";

export default {
  components: { QuestionEdit, Layout },
  data() {
    return {
      // form: {
      //   paper: {
      //     id: 8,
      //     totalScore: 123,
      //     adaptationDegree: 0.72,
      //     totalDifficulty: 3.0,
      //     knowledgeCoverage: 1.0,
      //     problems: null,
      //     paperProblems: null,
      //     isAuto: true,
      //   },
      //   problems: [
      //     {
      //       id: 15,
      //       createUserId: null,
      //       knowledgeId: 6,
      //       type: 1,
      //       title: "1-1的结果是什么",
      //       index: null,
      //       defaultScore: 1153,
      //       difficulty: 10,
      //       expend: ["123", "123", "1"],
      //     },
      //     {
      //       id: 18,
      //       createUserId: null,
      //       knowledgeId: 2,
      //       type: 2,
      //       title: "2+2的结果是什么",
      //       index: null,
      //       defaultScore: 1679,
      //       difficulty: 8,
      //       expend: [],
      //     },
      //     {
      //       id: 20,
      //       createUserId: null,
      //       knowledgeId: 4,
      //       type: 3,
      //       title:
      //         "为什么大学生大三要学习高数，是因为搞是很简单嘛？请以此为标题写一篇1000字论文",
      //       index: null,
      //       defaultScore: 1679,
      //       difficulty: 7,
      //       expend: [],
      //     },
      //   ],
      // },
      formLoading: false,
      answer: [],
      timer: null,
      form: { paper: {}, problems: {} },
    };
  },
  created() {
    let id = this.$route.query.id;
    let _this = this;
    console.log(id);
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true;
      attendExam({
        examId: id,
        studentId: 1,
      })
        .then((re) => {
          console.log(re);
          if (!re) {
            _this.$alert("id错误", {
              confirmButtonText: "返回首页",
              callback: (action) => {
                _this.$router.push("/paper");
              },
            });
          }
          getAllPapers().then((res) => {
            console.log(res);
            res.data.forEach((item) => {
              if (item.paper.id == this.$route.query.paperId) {
                console.log(item);
                this.form = item;
                this.initAnswer();
              }
            });
            _this.formLoading = false;
          });
        })
        .catch((e) => {
          _this.$alert("出现未知错误", {
            confirmButtonText: "返回首页",
            callback: (action) => {
              _this.$router.push("/paper");
            },
          });
        });
    } else {
      _this.$alert("id错误", {
        confirmButtonText: "返回首页",
        callback: (action) => {
          _this.$router.push("/paper");
        },
      });
    }
  },
  mounted() {},
  beforeDestroy() {
    window.clearInterval(this.timer);
  },
  methods: {
    formatSeconds(theTime) {
      return formatSeconds(theTime);
    },
    questionCompleted(completed) {
      return this.enumFormat(this.doCompletedTag, completed);
    },
    goAnchor(selector) {
      this.$el.querySelector(selector).scrollIntoView({
        behavior: "instant",
        block: "center",
        inline: "nearest",
      });
    },
    initAnswer() {
      let problems = this.form.problems;
      for (let tIndex in problems) {
        this.answer.push({
          answer: undefined,
          questionId: problems[tIndex].id,
          studentId: 1,
          examId: undefined,
        });
        // }
      }
    },
    submitForm() {
      let _this = this;
      console.log("12312", _this.answer);
      finishExam({
        studentId: 1,
        examId: this.$route.query.id,
        answer: _this.answer.map((item) => ({
          answer: item?.answer,
          questionId: item?.questionId,
        })),
      }).then((res) => {
        console.log(res);
      });
      // const alls = this.answer.map((item) => {
      //   return commitPractice(item);
      // });
      // console.log(alls);
      // Promise.all(alls)
      //   .then((re) => {
      //     if (re) {
      //       _this.$alert("考试结束", {
      //         confirmButtonText: "返回首页",
      //         callback: (action) => {
      //           _this.$router.push("/paper");
      //         },
      //       });
      //     } else {
      //       _this.$message.error(re);
      //     }
      //   })
      //   .catch((e) => {
      //     _this.$message.error(e);
      //   });
    },
  },
  computed: {
    ...mapGetters("enumItem", ["enumFormat"]),
    ...mapState("enumItem", {
      doCompletedTag: (state) => state.exam.question.answer.doCompletedTag,
    }),
  },
};
</script>

<style lang="scss" scoped>
.align-center {
  text-align: center;
}

.exam-question-item {
  padding: 10px;

  .el-form-item__label {
    font-size: 15px !important;
  }
}

.question-title-padding {
  padding-left: 25px;
  padding-right: 25px;
}
</style>
